//
//  TBWebViewController.m
//  Newapix
//
//  Created by APiX on 16/6/6.
//  Copyright © 2016年 APiX. All rights reserved.
//

#import "TBWebViewController.h"
#import "convertClass.h"
#import "CYHttpTool.h"
#import "CYUser.h"
#import "CYLoginHttpTool.h"
#import "DCPaymentView.h"
#import "CYDES3Util.h"
#import "CYJsonInfo.h"
#import "MBProgressHUD+LE.h"
#import "NSObject+MJKeyValue.h"
#import "UIAlertView+Block.h"

@interface TBWebViewController ()<UIWebViewDelegate>
@property (nonatomic, strong)UIWebView *webview;
@property (nonatomic, strong) UITextField *desTF;


@end

@implementation TBWebViewController

-(void)loadView
{
    UIWebView *webView = [[UIWebView alloc]init];
    self.view = webView;
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
     UIAlertView *zmfalert = [[UIAlertView alloc]initWithTitle:@"请输入交易密码" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确认", nil];
     [zmfalert setAlertViewStyle:UIAlertViewStyleSecureTextInput];
     [zmfalert show];
     [zmfalert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
          if (buttonIndex == 1) {
               _desTF = [zmfalert textFieldAtIndex:0];
               NSURL *url = [NSURL URLWithString:@"https://login.m.taobao.com/login.htm"];
               NSURLRequest *request = [NSURLRequest requestWithURL:url];
               UIWebView *webView = (UIWebView *)self.view;
               [webView loadRequest:request];
               webView.delegate = self;

          }
     }];
     
}
/**
 *  添加滑动返回
 */
- (void)handleSwipes:(UISwipeGestureRecognizer *)sender {
     if (sender.direction == UISwipeGestureRecognizerDirectionRight) {
          [[self navigationController] setNavigationBarHidden:NO animated:NO];
          [self.navigationController popViewControllerAnimated:YES];
     }
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL * url = [request URL];
    
    NSString * string = url.absoluteString;
    NSLog(@"*********%@",string);
    
    if ([string rangeOfString:@"h5.m.taobao.com"].location == NSNotFound) {
        return YES;
    } else if([string rangeOfString:@"h5.m.taobao.com"].location != NSNotFound){
        NSHTTPCookieStorage *myCookie = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSMutableDictionary *cookieDic = [NSMutableDictionary dictionary];
        for (NSHTTPCookie *cookie in [myCookie cookies] ) {
            if ([cookie.domain hasSuffix:@"taobao.com"]) {
                [cookieDic setValue:cookie.value forKey:cookie.name];
            }
        }
//#warning Value处替换您回调URL 如果没有可以空出来
         //测试地址：http://112.117.28.139:8058/phone/apix/getTaoBaoResult.htm   http://www.credit-manage.com:8058
        [cookieDic setValue:@"http://www.credit-manage.com:8058/phone/apix/getTaoBaoResult.htm" forKey:@"callback"];
        NSString *cookieJson = [convertClass JSONStringWith:cookieDic];
        [self sendCookieAndGetTokenWithcookJson:cookieJson];
        return NO;
    }
    
    return YES;
}

- (void)sendCookieAndGetTokenWithcookJson:(NSString *)cookJson
{
     [MBProgressHUD showMessage:nil toView:self.view];
    NSURL *url = [NSURL URLWithString:@"http://e.apix.cn/apixanalysis/tb/grant/ele_business/taobao/sdk"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSString *para = cookJson;
    request.HTTPBody = [para dataUsingEncoding:NSUTF8StringEncoding];
//#warning Value处请替换您自己的apix-key值
    [request setValue:@"d062038e5655449c65c772095c71a905" forHTTPHeaderField:@"apix-key"];
    NSURLSession *globleSession = [NSURLSession sharedSession];
    [[globleSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error&&data.length>0) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
             CYLog(@"--------------------------------------------------------------result= %@",result);
            if ([result[@"success"] intValue] ==1) {
//                 [MBProgressHUD hideHUDForView:self.view animated:YES];
//#warning 当success值为1的时候，爬取成功，demo中写入弹框提醒您是否成功，您可以酌情去掉
                 //成功后输入交易密码
                 CYUser *user = [CYLoginHttpTool userData].user;
                 NSString *desstr = [CYDES3Util encrypt:_desTF.text];
                 NSString *toekn = [result objectForKey:@"token"];
                 if (toekn && desstr) {
                      [MBProgressHUD showMessage:nil toView:self.view];
                      [CYHttpTool postWithURL:[CYURL shared].saveJuHeTaoBao params:@{@"userId":user.userId,@"token":user.token,@"apixToken":toekn,@"dealCode":desstr} success:^(id json) {
                           [MBProgressHUD hideHUDForView:self.view animated:YES];
                           
                           CYJsonInfo *jsoninfo = [CYJsonInfo objectWithKeyValues:json];
                           UIAlertView *backAlert = [[UIAlertView alloc]initWithTitle:@"提示" message:jsoninfo.message  delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                           [backAlert showAlertViewWithCompleteBlock:^(NSInteger buttonIndex) {
                                if (buttonIndex == 0) {
                                     [self.navigationController popViewControllerAnimated:YES];
                                     
                                }
                           }];
                           
                           
                           
                      } failure:^(NSError *error) {
                           [MBProgressHUD hideHUDForView:self.view];
                           CYAlertView(@"网络好像出家了,请稍后重试");
                      }];
                 }

                 
            }else{
                [self popToAlartViewWithTitle:@"获取失败"];
            }
        }else{
            NSLog(@"%@",error);
        }
    }]resume];
    
}
//成功或者失败后弹窗
- (void)popToAlartViewWithTitle:(NSString *)title
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *isCancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.view endEditing:YES];
    }];
    [alertController addAction:isCancel];
    [self presentViewController:alertController animated:YES completion:nil];
}
@end
